package com.zhucan.tenant.mongo;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoDatabase;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;

/**
 * @author My Lord zhuCan
 * @descriptionv 芒果客户端的数据库工厂
 * @since 2022-12-09 11:14
 **/
public class MongoMultiTenantFactory extends SimpleMongoClientDatabaseFactory {

    protected MongoContextHolder contextHolder;

    private static final Logger log = LoggerFactory.getLogger(MongoMultiTenantFactory.class);


    public MongoMultiTenantFactory(MongoClient client, String databaseName, MongoContextHolder contextHolder) {
        super(client, databaseName);
        this.contextHolder = contextHolder;
    }

    @Override
    protected MongoDatabase doGetMongoDatabase(String dbName) {
        String tenantDatabaseName = contextHolder.tenantDatabaseName();

        if (StringUtils.isBlank(tenantDatabaseName)) {
            log.error("Can not acquire tenant database of mongo from tenant context, Please ensured validity of tenant information !");
            //// todo: The exception must be throwing at here
        }

        log.info("Mongo database switched to new one that named : {}", tenantDatabaseName);

        return super.doGetMongoDatabase(tenantDatabaseName);
    }
}
